package com.ruoyi.common.core.utils;

import com.ruoyi.common.core.exception.ServiceException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";
    public static String YYYY_M = "yyyy-M";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /** 1秒 = 1000毫秒 */
    public static final long SECS = 1000;
    /** 1分 = 60000毫秒 */
    public static final long MIN = 60000;
    /** 1小时 = 3600000毫秒 */
    public static final long HOUR = 3600000;
    /** 1天 = 86400000毫秒 */
    public static final long DAY = 86400000;

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * @方法名：getMsecPoorFormat
     * @描述： 格式化时间差至毫秒
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2023/3/10 20:13
     */
    public static String getMsecPoorFormat(LocalDateTime startTime) {
        /**
         * 1 天=86400000 毫秒
         * 1 时(小时)=3600000 毫秒
         * 1 分(分钟)=60000 毫秒
         * 1 秒=1000 毫秒
         */
        long msec = ChronoUnit.MILLIS.between(startTime, LocalDateTime.now());
        return formatMillisecond(msec);
        /*if(msec < 1000){
            return msec + "毫秒";
        }else if(msec == 1000){
            return "1秒";
        }else if(msec > 1000 && msec < 60000){
            long second = msec / 1000;
            msec = msec % 1000;
            if(msec > 0){
                return second + (double) msec / 1000 + "秒";
            }
            return second + "秒";
        }else if(msec > 60000 && msec < 3600000){
            long minute = msec / 60000;
            msec = msec % 60000;
            long second = msec / 1000;
            msec = msec % 1000;
            String result = "";
            if(0 < minute){
                result += minute+"分";
            }
            if(0 < second){
                result += second;
                if(0 < msec){
                    result += (double) msec / 1000;
                }
                result += "秒";
            }else{
                result += "钟";
            }
            return result;
        }
        // 先不考虑超过1小时
        return null;*/
    }

    /**
     * 方法名: getMsecPoorFormat <br/>
     * 描述: 格式化毫秒 -- 时分秒毫秒 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/6/7 11:28 上午
     */
    public static String formatMillisecond(long ms) {
        if (ms < 1000) {
            return ms + "毫秒";
        } else if (ms < 60000) {
            long s = ms / 1000;
            ms = ms % 1000;
            if (ms == 0) {
                return s + "秒";
            }
            return Double.valueOf(s + "." + ms) + "秒";
        } else if (ms < 3600000) {
            long m = ms / 60000;
            ms = ms % 60000;
            if (ms == 0) {
                return m + "分";
            }
            return m + "分" + formatMillisecond(ms);
        }
        long h = ms / 3600000;
        ms = ms % 3600000;
        if (ms == 0) {
            return h + "时";
        }
        return h + "时" + formatMillisecond(ms);
    }

    public static String timeDistance(long ms) {
        if (ms <= 0) {
            return ms + "毫秒";
        }
        // 计算差多少天
        long day = ms / DAY;
        // 计算差多少小时
        long hour = ms % DAY / HOUR;
        // 计算差多少分钟
        long min = ms % DAY % HOUR / MIN;
        // 计算差多少秒
        long sec = ms % DAY % HOUR % MIN / SECS;
        // 计算差多少毫秒
        long millisecond = ms % SECS;

        StringBuilder result = new StringBuilder();

        if (day > 0) {
            result.append(day).append("天");
        }
        if (hour > 0) {
            result.append(hour).append("小时");
        }
        if (min > 0) {
            result.append(min).append("分钟");
        }
        if (sec > 0) {
            if (millisecond > 0) {
                result.append(Double.parseDouble(sec + "." + millisecond)).append("秒");
            } else {
                result.append(sec).append("秒");
            }
            return result.toString();
        }
        if (millisecond > 0) {
            result.append(millisecond).append("毫秒");
        }
        return result.toString();
    }

    /**
     * @方法名：formatTimeDifference
     * @描述： 传入开始时间，返回格式化后的时间差【返回格式xx天xx小时xx分钟】
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2023/2/10 15:16
     */
    public static String formatTimeDifference(Date startTime){
        return getDatePoor(startTime,getNowDate());
    }

    /**
     * @方法名：getDatePoorFormat
     * @描述： 格式化传入时间和当前时间的时间差
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2023/2/25 17:33
     */
    public static String getDatePoorFormat(LocalDateTime startTime)
    {
        return computedTimeCheckFormat(startTime,LocalDateTime.now());
    }

    /**
     * @方法名：computedTimeCheckFormat
     * @描述： 格式化LocalDateTime的时间差
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2021/4/2 21:10
     */
    public static String computedTimeCheckFormat (LocalDateTime startTime, LocalDateTime endTime) {

        //秒
        long seconds = ChronoUnit.SECONDS.between(startTime, endTime);
        //转换天数
        long days = seconds / 86400;
        //剩余秒数
        seconds = seconds % 86400;
        //转换小时数
        long hours = seconds / 3600;
        //剩余秒数
        seconds = seconds % 3600;
        //转换分钟
        long minutes = seconds / 60;
        //剩余秒数
        seconds = seconds % 60;
        String result = "";
        if(0 < days){
            result += days+"天";
        }
        if(0 < hours){
            result += hours+"小时";
        }
        if(0 < minutes){
            result += minutes+"分";
        }
        if(0 < seconds){
            result += seconds+"秒";
        }else{
            result += "钟";
        }
        return result;
    }

    /**
     * 计算两个时间差(返回格式xx天xx小时xx分钟)
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * @方法名: greaterThan
     * @描述: 判断传入的时间是否大于当前时间 年月日对比
     * @作者: LeiYang
     * @时间: Created in 2023/3/23 14:28
     */
    public static Boolean greaterThan(Date date) {
        if (date == null) {
            return false;
        }
        Date date1 = parseDate(parseDateToStr(YYYY_MM_DD, date));
        Date date2 = parseDate(parseDateToStr(YYYY_MM_DD, getNowDate()));
        return date1.compareTo(date2) > 0;
    }

    /**
     * @方法名: greaterThan
     * @描述: 给定的第一个日期是否大于第二个日期 (年月日判断)
     * @作者: LeiYang
     * @时间: Created in 2023/4/21 17:02
     */
    public static Boolean greaterThan(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return null;
        }
        Date dateOne = parseDate(parseDateToStr(YYYY_MM_DD, date1));
        Date dateTwo = parseDate(parseDateToStr(YYYY_MM_DD, date2));
        return dateOne.compareTo(dateTwo) > 0;
    }

    /**
     * @方法名: greaterThanOrEquals
     * @描述: 判断传入的时间是否大于或等于当前时间 年月日对比
     * @作者: LeiYang
     * @时间: Created in 2023/3/23 14:27
     */
    public static Boolean greaterThanOrEquals(Date date) {
        if (date == null) {
            return null;
        }
        Date date1 = parseDate(parseDateToStr(YYYY_MM_DD, date));
        Date date2 = parseDate(parseDateToStr(YYYY_MM_DD, getNowDate()));
        return date1.compareTo(date2) >= 0;
    }

    /**
     * @Method greaterThanOrEquals <br/>
     * @Description 判断date1 >= date2 <br/>
     * @Param date1
     * @Param date2 <br/>
     * @Author Cao.Yu <br/>
     * @Date 2023/8/8 14:01 <br/>
     */
    public static Boolean greaterThanOrEquals(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return false;
        }
        return parseDate(parseDateToStr(YYYY_MM_DD, date1)).compareTo(parseDate(parseDateToStr(YYYY_MM_DD, getNowDate()))) >= 0;
    }

    /**
     * 方法名: judge <br/>
     * 描述: 判断日期是否在一日期区间 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/6/12 3:28 下午
     */
    public static boolean judgeDateBetweenAnd(Date date, Date startDate, Date endDate) {
        checkOrSwapDate(startDate, endDate);
        return date.compareTo(startDate) >= 0 && date.compareTo(endDate) <= 0;
    }

    /**
     * 方法名: formatDateToZeroPoint <br/>
     * 描述: 格式化日期, 年月日 00:00:00 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/4/19 3:10 下午
     */
    public static Date formatDateToZeroPoint(Date date) {
        if (date == null) {
            return formatDateToZeroPoint(getNowDate());
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        date.setTime(calendar.getTimeInMillis());
        return date;
    }

    public static void formatDateToZeroPoint(Date... ds) {
        if (ArrayUtils.isNotEmpty(ds)) {
            for (Date d : ds) {
                formatDateToZeroPoint(d);
            }
        }
    }

    /**
     * 方法名: checkOrSwapDate <br/>
     * 描述: 格式化两个日期大小关系 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/5/26 4:04 下午
     */
    public static void checkOrSwapDate(Date startDate, Date endDate) {
        formatDateToZeroPoint(startDate, endDate);
        checkOrSwapDateTime(startDate, endDate);
    }

    /**
     * 方法名: checkOrSwapDateTime <br/>
     * 描述: 格式化两个日期时间大小关系 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/6/12 3:26 下午
     */
    public static void checkOrSwapDateTime(Date startDate, Date endDate) {
        if (startDate.compareTo(endDate) > 0) {
            long t = startDate.getTime();
            startDate.setTime(endDate.getTime());
            endDate.setTime(t);
        }
    }

    /**
     * 方法名: getDatesBetween <br/>
     * 描述: 获取两日期之间指定间隔日期 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/4/17 4:19 下午
     */
    public static List<Date> getDatesBetween(Date startDate, Date endDate, int steps) {
        checkOrSwapDate(startDate, endDate);
        LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 两日期间隔多少天
        long numOfDaysBetween = ChronoUnit.DAYS.between(startLocalDate, endLocalDate);
        long days = numOfDaysBetween / steps;
        List<Date> list = new ArrayList<>();
        list.add(startDate);
        for (int i = 1; i <= days; i++) {
            list.add(toDate(startLocalDate.plusDays((long) steps * i)));
        }
        return list;
    }

    /**
     * @Method toLocalDate <br/>
     * @Description date 转 LocalDate <br/>
     * @Param dateToConvert <br/>
     * @Author Cao.Yu <br/>
     * @Date 2023/7/10 17:06 <br/>
     * @Return java.time.LocalDate
     */
    public static LocalDate toLocalDate(Date dateToConvert) {
        return dateToConvert.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
    }

    /**
     * @Method getDateBetween <br/>
     * @Description 计算两日期差值 <br/>
     * @Param start
     * @Param end <br/>
     * @Author Cao.Yu <br/>
     * @Date 2023/7/10 17:09 <br/>
     * @Return long
     */
    public static int getDateBetween(Date start, Date end) {
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(start);
        int day1= aCalendar.get(Calendar.DAY_OF_YEAR);

        aCalendar.setTime(end);
        int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
        return day2 - day1;
    }


    /**
     * @Method getMonthBetween <br/>
     * @Description 获取两月份之间所有月份集合(包含起始月份) 默认格式yyyy-MM <br/>
     * @Param minDate
     * @Param maxDate <br/>
     * @Author Cao.Yu <br/>
     * @Date 2023/7/19 17:28 <br/>
     */
    public static List<Date> getMonthBetween(Date minDate, Date maxDate) {
        return getMonthBetween(minDate, maxDate, DateUtils.YYYY_MM);
    }

    /**
     * @Method getMonthBetween <br/>
     * @Description 获取两月份之间所有月份集合(包含起始月份) <br/>
     * @Param minDate
     * @Param maxDate <br/>
     * @Author Cao.Yu <br/>
     * @Date 2023/7/19 17:28 <br/>
     */
    public static List<Date> getMonthBetween(Date minDate, Date maxDate, String format) {
        List<Date> result = new ArrayList<>();
        // 格式化为年月
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(minDate);
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(maxDate);
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        while (min.before(max)) {
            try {
                result.add(DateUtils.parseDate(sdf.format(min.getTime()), format));
            } catch (ParseException e) {
                e.printStackTrace();
                throw new ServiceException("系统错误！");
            }
            min.add(Calendar.MONTH, 1);
        }
        return result;
    }


    /**
     * 方法名: getDateListBetween <br/>
     * 描述: 根据两日期与指定周期天数, 生成周期时间段  <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/4/19 4:29 下午
     */
    public static List<List<Date>> getDateListBetween(Date startDate, Date endDate, int cycleDays) {
//        System.err.println("cycleDays: " + cycleDays);
        // 格式化时间为 年月日 00:00:00
        formatDateToZeroPoint(startDate);
        formatDateToZeroPoint(endDate);
        if (startDate.compareTo(endDate) > 0) {
            Date transfer = startDate;
            startDate = endDate;
            endDate = transfer;
        }
        LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//        System.err.println("startLocalDate==>"+startLocalDate);
        LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//        System.err.println("endLocalDate==>"+endLocalDate);
        // 两日期间隔多少天
        long numOfDaysBetween = ChronoUnit.DAYS.between(startLocalDate, endLocalDate);
        //numOfDaysBetween += 1;
        // 多少个周期
        long cycles = numOfDaysBetween / cycleDays;
        List<List<Date>> result = new ArrayList<>();
        List<Date> list = new ArrayList<>();
        if (cycles < 1) {
            list.add(startDate);
            list.add(endDate);
            result.add(list);
            return result;
        }
        // 1-30号  7天一个周期  1-7 8-14 15-21 22-28
        for (int i = 1; i <= cycles; i++) {
            list = new ArrayList<>();
            list.add(toDate(startLocalDate.plusDays((long) cycleDays * (i-1))));
            list.add(toDate(startLocalDate.plusDays((long) cycleDays * i - 1)));
            result.add(list);
        }

        //if (numOfDaysBetween % cycleDays != 0) {
        if (endDate.compareTo(list.get(1)) > 0) {
            // 最后一截不满足一个周期, 取到最后一天
            list = new ArrayList<>();
            list.add(toDate(startLocalDate.plusDays((long) cycleDays * cycles)));
            list.add(endDate);
            result.add(list);
        }
        return result;
    }

    /**
     * 方法名: addDate <br/>
     * 描述: 日期增加/减少任意天数 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/4/28 11:25 上午
     */
    public static Date addDate(Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }

    /**
     * 方法名: indexOf <br/>
     * 描述: 检索日期在哪个时间段 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/4/28 12:35 下午
     */
    public static int indexOf(List<List<Date>> dateListBetween, Date date) {
        // 时间段内时间有序 ----->
        if (dateListBetween.get(0).get(0).compareTo(date) > 0 || dateListBetween.get(dateListBetween.size() - 1).get(1).compareTo(date) < 0) {
            // 最小日期大于date || 最大日期小于date
            return -1;
        }
        for (int i = 0; i < dateListBetween.size(); i++) {
            List<Date> list = dateListBetween.get(i);
            if (list.get(0).compareTo(date) <= 0 && list.get(1).compareTo(date) >= 0) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 方法名: getDayOfWeek <br/>
     * 描述: 获取星期几 <br/>
     * return: 1~6, 周日返回0 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/5/25 5:23 下午
     */
    public static int getDayOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        return cal.get(Calendar.DAY_OF_WEEK) - 1;
    }

    public static int getYear(Date date) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        return cal.get(Calendar.YEAR);
    }

    public static int getMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        return cal.get(Calendar.MONTH) + 1;
    }

    /**
     * 方法名: getByCalendar <br/>
     * 描述: 返回给定日历字段的值 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/5/29 4:36 下午
     */
    public static int getByCalendar(Date date, int field) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        return cal.get(field);
    }

    /**
     * 方法名: isWeekend <br/>
     * 描述: 是周末 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/5/25 5:38 下午
     */
    public static boolean isWeekend(Date date) {
        int dayOfWeek = getDayOfWeek(date);
        return dayOfWeek == 6 || dayOfWeek == 0;
    }

    /**
     * 方法名: getDaysBetween <br/>
     * 描述: 两日期间隔多少天 <br/>
     * 作者: LGF <br/>
     * 日期: Created in 2023/7/11 10:19 上午
     */
    public static int getDaysBetween(Date startDate, Date endDate) {
        checkOrSwapDate(startDate, endDate);
        return (int) ((endDate.getTime() - startDate.getTime()) / (1000 * 3600 * 24));
    }

}
